package com.xxgg.system.mybatis;

import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.xxgg.system.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.Date;

@Slf4j
@Component
public class MyMetaObjectHandler implements MetaObjectHandler {
    @Resource
    UserService userService;

    @Override
    public void insertFill(MetaObject metaObject) {
        log.info("start insert fill ....");
        this.strictInsertFill(metaObject, "createTime", () -> new Date(System.currentTimeMillis()), Date.class);
        this.strictInsertFill(metaObject, "updateTime", () -> new Date(System.currentTimeMillis()), Date.class);

        try {
            String userName = userService.getById(StpUtil.getLoginId().toString()).getUserName();
            this.strictInsertFill(metaObject, "createBy", () -> userName, String.class);
            this.strictInsertFill(metaObject, "updateBy", () -> userName, String.class);
        }catch (Exception ignored){

        }

    }

    @Override
    public void updateFill(MetaObject metaObject) {
        log.info("start update fill ....");
        this.strictUpdateFill(metaObject, "updateTime", () -> new Date(System.currentTimeMillis()), Date.class);

        try {
            String userName = userService.getById(StpUtil.getLoginId().toString()).getUserName();
            this.strictUpdateFill(metaObject, "updateBy", () -> userName, String.class);
        }catch (Exception ignored){

        }
    }
}